﻿(function($) {
    $.fn.translate = function(options) {
        //Build main options before element iteration
        var opts = $.extend({}, $.fn.translate.defaults, options);
        //Iterate and reformat each matched element
        return this.each(function() {
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
            $(this).click(function() {
                if ($('#translate-dialog').length > 0) {
                    $('#translate-dialog').remove();
                    return false;
                }
                var $anchor = $(this);
                var $dialog = $('<div id="translate-dialog"><img src="' + o.imageUrl + '" alt="Google Translate" /><p>Use Google to translate the web site. We take no responsibility for the accuracy of the translation.</p><label for="languages">Choose language:</label><select id="languages"></select></div>');
                for (var lang in google.language.Languages) {
                    if (lang !== "UNKNOWN" && google.language.isTranslatable(google.language.Languages[lang])) {
                        $dialog.find('#languages').append('<option value="' + google.language.Languages[lang] + '">' + lang + '</option>');
                    }
                }
                $anchor.after($dialog);
                $('#translate-dialog select').change(function() {
                    document.location.href = $anchor.attr('href').replace("hl=en", "hl=" + $('#translate-dialog select').val());
                });
                $('#translate-dialog').click(function(e) {
                    e.stopPropagation();
                });
                $('html').click(function() {
                    $('#translate-dialog').remove();
                });
                return false;
            });
        });
    }
    $.fn.translate.defaults = {
        imageUrl: ''
    };
})(jQuery);